package com.hbsoft.util;

import com.hb.util.HttpUtil;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.config.SysConfigInfo;
import com.hbsoft.wechat.bean.WxAappQrCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Component
public class WechatUtil {
	
	@Autowired
	public SysConfigInfo sysConfigInfo;

	private String wxAppGetOpenidByCodeURL = "https://api.weixin.qq.com/sns/jscode2session";

	private String wxAppGetAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	private final static String wxAppQrCodeUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN";

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	public String getWXAppOpenidByCodeUrl()  {
		StringBuffer sb = new StringBuffer();
		sb.append(wxAppGetOpenidByCodeURL + "?");
		sb.append("appid=" + sysConfigInfo.getAppid());
		sb.append("&secret=" + sysConfigInfo.getAppSecret());
		sb.append("&js_code=JSCODE");
		sb.append("&grant_type=authorization_code");
		return sb.toString();
	}

	public String getWXAppOpenidByCode(String code) throws Exception {
		logger.info("获取openid开始，code：{}",code);
		String openid = null;
		if(StringUtils.isNotBlank(code)){
			String url = getWXAppOpenidByCodeUrl().replace("JSCODE",code);
			logger.info("获取openid Url:{}",url);
			String result = HttpUtil.sendGet(url);
			logger.info("获取openid 返回值：{}",result);
			Map<String,Object> map = GsonUtil.fromJson(result,Map.class);
			openid = (String) map.get("openid");
		}
		logger.info("获取openid结束，openid：{}",openid);
		return openid;
	}


	public Map<String,Object> getWXAppOpenidAndSessionKeyByCode(String code) throws Exception {
		logger.info("获取openid开始，code：{}",code);
		Map<String,Object> map = new HashMap<>();
		if(StringUtils.isNotBlank(code)){
			String url = getWXAppOpenidByCodeUrl().replace("JSCODE",code);
			logger.info("获取openid Url:{}",url);
			String result = HttpUtil.sendGet(url);
			logger.info("获取openid 返回值：{}",result);
			map = GsonUtil.fromJson(result,Map.class);
			//openid = (String) map.get("openid");
			//sessionKey = (String) map.get("session_key");
		}
		return map;
	}

	public String getWxAppAccessToken()
	{
		String access_token = (String)Constant.tokenMap.get("access_token");
		if (access_token == null) {
			access_token = getWxAppAccessTokenTime();
		}
		return access_token;
	}

	public String getWxAppAccessTokenTime()
	{
		logger.info("定时获取token开始");
		wxAppGetAccessTokenURL = wxAppGetAccessTokenURL.replace("APPID", sysConfigInfo.getAppid());
		wxAppGetAccessTokenURL = wxAppGetAccessTokenURL.replace("APPSECRET", sysConfigInfo.getAppSecret());
		String result = HttpUtil.sendGet(wxAppGetAccessTokenURL);
		logger.info("获取token返回值：{}",result);
		Map<String, Object> map = (Map)GsonUtil.fromJson(result, Map.class);
		String access_token = (String)map.get("access_token");
		Constant.tokenMap.put("access_token", access_token);
		return access_token;
	}


	public String getWxAappQrCode(String qrParam) {
		logger.info("生成小程序码开始，qrParam:{}",qrParam);
		String fileName = "";
		try {

			WxAappQrCode wxAapp = new WxAappQrCode();
			if(StringUtils.isBlank(qrParam)){
				wxAapp.setPath("pages/index/index");
				qrParam = "qrCode";
			}else{
				wxAapp.setPath("pages/index/index?qrParam="+qrParam);
			}
			wxAapp.setWidth("300");
			String url = wxAppQrCodeUrl.replace("ACCESS_TOKEN",getWxAppAccessToken());
			String paramJson = GsonUtil.toJson(wxAapp);
			fileName = qrParam + ".jpg";

			String path =  ResourceUtils.getURL("classpath:").getPath()+"static/img/" + fileName;
			sendJSONPostReturnInputStrem(url,paramJson,path,null,"utf-8",6000,6000);
		}catch (Exception e){
			e.printStackTrace();
			logger.info("生成小程序码异常",e);
		}
		logger.info("生成小程序码结束，qrParam:{}",qrParam);
		return sysConfigInfo.getQrCodePath()+ fileName;
	}

	private void sendJSONPostReturnInputStrem(String url, String jsonParam, String path,Map<String, String> headerInfo, String charSet,
												   int timeOut, int socketTimeout) {
		String strResult = null;
		CloseableHttpClient httpCilent = null;
		HttpPost httpPost = null;
		RequestConfig requestConfig = null;
		CloseableHttpResponse response = null;
		StringEntity entity = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			if (jsonParam != null && !jsonParam.isEmpty()) {
				entity = new StringEntity(jsonParam, charSet);
			}
			httpCilent = HttpClients.createDefault();
			httpPost = new HttpPost(url);
			if (entity != null) {
				httpPost.setEntity(entity);
			}
			requestConfig = RequestConfig.custom()//
					.setConnectionRequestTimeout(timeOut)// 设置请求连接超时时间
					.setConnectTimeout(timeOut)// 设置连接超时时间
					.setSocketTimeout(socketTimeout)// 数据传输过程中数据包之间间隔的最大时间
					.build();
			httpPost.setConfig(requestConfig);
			httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=" + charSet));
			// httpPost.setHeader(new BasicHeader("Accept",
			// "text/plain;charset=" + charSet));
			httpPost.setHeader(new BasicHeader("Accept", "application/json;charset=" + charSet));
			if (headerInfo != null && !headerInfo.isEmpty()) {
				for (String key : headerInfo.keySet()) {
					httpPost.setHeader(new BasicHeader(key, headerInfo.get(key)));
				}
			}
			response = httpCilent.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			switch (statusCode) {
				case HttpStatus.SC_OK:
					HttpEntity httpEntity=response.getEntity();
					inputStream=httpEntity.getContent();
					break;
				case HttpStatus.SC_NOT_FOUND:
					System.out.println("POST请求404未找到信息");
					break;
				case HttpStatus.SC_INTERNAL_SERVER_ERROR:
					System.out.println("POST请求500请求地址发生异常");
					break;
				default:
					System.out.println("POST请求错误状态码:" + statusCode);
					break;
			}
			File file = new File(path);
			if (!file.exists()) {
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file);
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = inputStream.read(buf, 0, 1024)) != -1) {
				outputStream.write(buf, 0, len);
			}
			outputStream.flush();

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpPost != null) {
				try {
					httpPost.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			}
			if (httpCilent != null) {
				try {
					httpCilent.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	

	
}
